package io.renren.config;

import cn.dev33.satoken.exception.NotLoginException;
import io.renren.constant.BizSystemException;
import io.renren.enums.ResultCodeEnum;
import io.renren.util.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截其他运行时异常
     */
//    @ResponseBody
//    @ExceptionHandler(RuntimeException.class)
//    public ApiResult<?> handlerRuntimeException(RuntimeException e) {
//        log.error("[invoke] 运行时异常:", e);
//        return ApiResult.fail(e.getMessage());
//    }

    /**
     * 拦截业务异常
     */
    @ResponseBody
    @ExceptionHandler(BizSystemException.class)
    public ApiResult<?> handlerBizException(BizSystemException e) {
        log.error("[BizSystemException] 业务异常:", e);
        return ApiResult.build(e.getCode(), e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(NotLoginException.class)
    public ApiResult<?> handlerNotLoginException(NotLoginException nle) {
        // satoken 异常处理
        String message = "";
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供Token";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "未提供有效的Token";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "登录信息已过期，请重新登录";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "您的账户已在另一台设备上登录，如非本人操作，请立即修改密码";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "已被系统强制下线";
        } else {
            message = "当前会话未登录";
        }
        // 返回给前端
        return ApiResult.build(ResultCodeEnum.ADMIN_LOGIN_AUTH.getCode(), message);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public ApiResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败：");
        for(FieldError fieldError : bindingResult.getFieldErrors()){
            sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(",");
        }
        String message = sb.substring(0, sb.length() - 1);
        return ApiResult.build(ResultCodeEnum.PARAM_ERROR.getCode(), message);
    }

}
